package org.vdab.projects.tasks.shared.entities.impl;

import java.util.HashSet;
import java.util.Set;

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import org.vdab.projects.tasks.client.util.ICommand;
import org.vdab.projects.tasks.client.util.MessageGuard;
import org.vdab.projects.tasks.shared.EntityManager;
import org.vdab.projects.tasks.shared.entities.ITask;
import org.vdab.projects.tasks.shared.entities.ITaskBook;
import org.vdab.projects.tasks.shared.entities.ITaskList;

@PersistenceCapable
public class TaskList extends BaseEntity<TaskList> implements ITaskList{
	
//	@SuppressWarnings("unused")
//	@PrimaryKey
//	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
//	@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
//	private String key;
	
	
	@Persistent
	private String name;	

	// This Set of Keys is used to describe a many-to-many relationship
	// as described on
	// http://code.google.com/intl/nl-NL/appengine/docs/java/datastore/jdo/relationships.html#Unowned_Relationships
	@Persistent
	private Set<String> parrentTodoBookKeys = new HashSet<String>();

	//http://code.google.com/intl/nl-NL/appengine/docs/java/datastore/jdo/relationships.html#Owned_One_to_Many_Relationships
	@Persistent(mappedBy="parrentTaskList")
	private Set<Task> myTasks = new HashSet<Task>();

	public TaskList(){	
	}
	
	public TaskList(String name){
		this.name = name;
	}
	
	public void addToTodobook(ITaskBook taskBook) throws Exception {
		if(!this.parrentTodoBookKeys.contains(taskBook.getKey())){			
			this.parrentTodoBookKeys.add(taskBook.getKey());
			taskBook.addTaskList(this);
		}		
	}


	@Override
	public void addTask(ITask task) throws Exception {
		final TaskList ft = this;
		task.execute(new ICommand<Task>() {			
			@Override
			public void execute(Task entity) throws Exception {
				entity.setParrent(ft);
				myTasks.add(entity);	
			}
		});
	}


	@Override
	public String getDisplayText() {		
		return this.name + "(" + this.getKey() + ")";
	}


	@Override
	public TaskList save() throws Exception {
		EntityManager.get().saveTaskList(this);
		return this;
	}

	@Override
	public Set<ITask> getTasks() {
		if(myTasks==null){
			MessageGuard.Log("myTask==NULL");
		}else{			
			MessageGuard.Log("In TaskList.getTasks(). Containing " + myTasks.size() + " tasks.");
		}
		return new HashSet<ITask>(myTasks);
	}	
}
